#include "semephore_try.h"


typedef struct thread_args
{
    int thread_num;
    char * thread_name;
} thread_args;


static int num = 10;
sem_t sem;

void * add(void * args){
    thread_args * thd_args = (thread_args *) args;
    // == 等待全局信号量
    printf("\e[1;31m===============%s等待信号量===============\e[0m\n", thd_args->thread_name);
    sem_wait(&sem);
    printf("\e[1;33m===============%s获得信号量===============\e[0m\n", thd_args->thread_name);
    printf("\e[1;32m==================%s开始==================\e[0m\n", thd_args->thread_name);
    printf("%s: num初始值 --> %d\n", thd_args->thread_name, num);
    for(int i=0; i<10; i++){
        printf("\e[1;35m%s: num加一后 --> %d\e[0m\n", thd_args->thread_name, ++num);
        printf("\e[1;35m%s: 睡眠1s\e[0m\n", thd_args->thread_name);
        sleep(1);
    }
    printf("\e[1;32m==================%s结束==================\e[0m\n", thd_args->thread_name);
}

void * subs(void * args){
    thread_args * thd_args = (thread_args *) args;
    printf("\e[1;32m==================%s开始==================\e[0m\n", thd_args->thread_name);
    printf("%s: num初始值 --> %d\n", thd_args->thread_name, num);
    for (int i=0; i<10; i++){
        printf("\e[1;34m%s: num减一后 --> %d\e[0m\n", thd_args->thread_name, --num);
        printf("\e[1;34m%s: 睡眠1s\e[0m\n", thd_args->thread_name);
        sleep(1);
    }
    printf("\e[1;33m===============%s发送信号量===============\e[0m\n", thd_args->thread_name);
    sem_post(&sem);
    printf("\e[1;32m]==================%s结束==================\e[0m\n", thd_args->thread_name);
}


int main(void){ 
    printf("\e[1;32m==================主线程开始==================\e[0m\n");
    pid_t t_id1, t_id2;
    thread_args * add_args = (thread_args *) malloc(sizeof(thread_args));
    if (add_args == NULL){
        printf("创建add线程参数失败，退出...\n");
        return -1;
    }
    add_args->thread_name = "add thread";
    add_args->thread_num = 1;

    thread_args * subs_args = (thread_args *) malloc(sizeof(thread_args));
    if (subs_args == NULL){
        printf("创建subs线程参数失败，退出...\n");
        return -1;
    }
    subs_args->thread_name = "subs thread";
    subs_args->thread_num = 1;

    // printf("main: %d\n", num);
    printf("主线程中num初始值: %d\n", num);


    pthread_create(&t_id2, NULL, add, (void *) add_args);
    pthread_create(&t_id1, NULL, subs, (void *) subs_args);
    sleep(21);
    // void * ans1, *ans2;
    // pthread_join(t_id1, NULL);
    // pthread_join(t_id2, NULL);
    printf("主线程中num最终值: %d\n", num);
    printf("\e[1;32m==================主线程结束==================\e[0m\n");
    return 0;
}